<?php

namespace App\Http\Controllers;

use App\Models\Post;
use App\Repositories\PostsRepositories;
use Illuminate\Http\Request;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //$this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index(PostsRepositories $postsRepositories)
    {
        $last=$postsRepositories->last(8);
       //dump($last->toArray());

        return frontend('default.home',compact('last'));
    }
    public function post($id,PostsRepositories $postsRepositories)
    {
        $post=$postsRepositories->find($id);
        //dump($post->toArray());
        return frontend('default.post',compact('post'));
    }

    public function show($slug,PostsRepositories $postsRepositories)
    {
        $post=$postsRepositories->slug($slug);
        //dump($post->toArray());
        return frontend('default.post',compact('post'));
    }

    public function page($id,PostsRepositories $postsRepositories)
    {
        $post=$postsRepositories->find($id);
        //dump($post->toArray());
        return frontend('default.post',compact('post'));
    }

    public function category($id=0,Request $request,PostsRepositories $postsRepositories)
    {
        $id=intval($id);
        $txt = $request->input('searchu');
        $perPage = $request->input('per_num',20); //每页页码
        $query = Post::query()->with(['manyCategory','manyTag'])->whereHas('manyCategory',function ($query) use($id) {
            if($id > 0)
            {
                $query->where('id',$id);
            }
        })->orderBy('created_at', 'desc');
        $result = $query->paginate($perPage);
        $paginator = $result->render();
        $result =  collect($result)->toArray();
        //dump($result['data']);

        $posts = $result['data'];
        $total = $result['total'];//总页码
        $current_page = $result['current_page'];//当前页
        return frontend('default.category',compact('txt','posts','paginator' ,'total','current_page','perPage'));

    }
}
